package edu.uc.labs.MobilePrinting.Fetch;

import edu.uc.labs.MobilePrinting.Configurator;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import org.apache.log4j.Logger;

/**
 * 
 * Sends a GET request to a server and receives and writes text file that
 * becomes the PPD file to use for printer installation
 * 
 */
public class PPDFetcher {

	private String server, zone, queue, os;
	private String input = "";
	private URL u;
	private URLConnection conn;
	public Configurator conf = new Configurator();
	public Logger logger = conf.getLogger();

	public PPDFetcher(String server, String zone, String queue, String osname) {

		this.server = server;
		this.zone = zone;
		this.queue = queue;
		this.os = osname;

		try {
			u = new URL(buildUrl());
		} catch (MalformedURLException ex) {
			logger.error(ex.toString());
		}
		connect();
	}

	private String buildUrl() {
		String url = "http://" + this.server + "/ppd/" + this.zone + "/"
				+ this.os + "/" + this.queue + ".ppd";
		logger.debug("The url to fetch the ppd: " + url);
		return url;

	}

	public void connect() {
		try {
			conn = u.openConnection();
			InputStream instream = conn.getInputStream();
			Scanner in = new Scanner(instream);
			while (in.hasNextLine()) {
				input += in.nextLine() + "\n";
			}
		} catch (IOException ex) {
			logger.error(ex.toString());
		}

	}

	public void writeToFile() {
		try {

			// If the directory doesn't exist, create it...
			File theDir = new File(Configurator.CACHEDIR + Configurator.DELIM
					+ "ppd" + Configurator.DELIM + this.zone);
			if (!theDir.exists()) {
				logger.debug(theDir.getAbsolutePath() + " is gonna be created");
				theDir.mkdir();
			}

			// Then write the .ppd file...
			String file_name = Configurator.CACHEDIR + Configurator.DELIM
					+ "ppd" + Configurator.DELIM + this.zone
					+ Configurator.DELIM + this.queue + ".ppd";
			FileWriter fstream = new FileWriter(file_name);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(input);
			out.close();
		} catch (IOException ex) {
			logger.error(ex);
		}

	}

}
